package com.tjf.lib_network;

import android.text.TextUtils;

import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.sse.RealEventSource;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

public class OkSseClient {

    public static void getSmTl4EventId(String url,  EventSourceListener sourceListener) {

        Request.Builder mRequestBuilder = new Request.Builder();//请求对象的构建者
        mRequestBuilder.url(url);

        Request request = mRequestBuilder.build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(1, TimeUnit.DAYS)
                .readTimeout(1, TimeUnit.DAYS)//这边需要将超时显示设置长一点，不然刚连上就断开，之前以为调用方式错误被坑了半天
                .build();

        // 实例化EventSource，注册EventSource监听器
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            private long callStartNanos;

            private void printEvent(String name) {

            }

            @Override
            public void onOpen(EventSource eventSource, Response response) {
//                printEvent("onOpen");
                sourceListener.onOpen(eventSource, response);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
//                printEvent("onEvent");
//                System.out.println(data);//请求到的数据
                sourceListener.onEvent(eventSource, id, type, data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
//                printEvent("onClosed");
                sourceListener.onClosed(eventSource);
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
//                printEvent("onFailure");//这边可以监听并重新打开
                sourceListener.onFailure(eventSource, t, response);
            }
        });
        realEventSource.connect(okHttpClient);//真正开始请求的一步
    }

    public static void getChatAi(String url, String json, HashMap<String, String> mHeaderMap, EventSourceListener sourceListener) {

        Request.Builder mRequestBuilder = new Request.Builder();//请求对象的构建者
        mRequestBuilder.url(url);
        if (mHeaderMap != null) {
            for (String key : mHeaderMap.keySet()) {
                mRequestBuilder.addHeader(key, mHeaderMap.get(key));
            }
        }
        if (!TextUtils.isEmpty(json)) {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式，
            mRequestBuilder.post(RequestBody.create(JSON, json));
        }
        if (!TextUtils.isEmpty(SpSaveUtils.getToken())) {
            mRequestBuilder.addHeader("AUTHORIZATION", "Bearer " + SpSaveUtils.getToken());
        }
        Request request = mRequestBuilder.build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(1, TimeUnit.DAYS)
                .readTimeout(1, TimeUnit.DAYS)//这边需要将超时显示设置长一点，不然刚连上就断开，之前以为调用方式错误被坑了半天
                .build();

        // 实例化EventSource，注册EventSource监听器
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            private long callStartNanos;

            private void printEvent(String name) {
//                long nowNanos = System.nanoTime();
//                if (name.equals("callStart")) {
//                    callStartNanos = nowNanos;
//                }
//                long elapsedNanos = nowNanos - callStartNanos;
//                System.out.printf("=====> %.3f %s%n", elapsedNanos / 1000000000d, name);
            }

            @Override
            public void onOpen(EventSource eventSource, Response response) {
//                printEvent("onOpen");
                sourceListener.onOpen(eventSource, response);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
//                printEvent("onEvent");
//                System.out.println(data);//请求到的数据
                sourceListener.onEvent(eventSource, id, type, data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
//                printEvent("onClosed");
                sourceListener.onClosed(eventSource);
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
//                printEvent("onFailure");//这边可以监听并重新打开
                sourceListener.onFailure(eventSource, t, response);
            }
        });
        realEventSource.connect(okHttpClient);//真正开始请求的一步
    }


    public static void getChatAiFrom(String url, String filePath, HashMap<String, String> mParamMap, EventSourceListener sourceListener) {

        Request.Builder mRequestBuilder = new Request.Builder();//请求对象的构建者
        mRequestBuilder.url(url);

        if (!TextUtils.isEmpty(SpSaveUtils.getToken())) {
            mRequestBuilder.addHeader("AUTHORIZATION", "Bearer " + SpSaveUtils.getToken());
        }
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            if (mParamMap != null) {
                for (String key : mParamMap.keySet()) {
                    builder.addFormDataPart(key, mParamMap.get(key));
                }
            }
            builder.addFormDataPart("file", file.getName(),
                    RequestBody.create(MediaType.parse("audio/*"), file));
            mRequestBuilder.post(builder.build());
        }

        Request request = mRequestBuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(1, TimeUnit.DAYS)
                .readTimeout(1, TimeUnit.DAYS)//这边需要将超时显示设置长一点，不然刚连上就断开，之前以为调用方式错误被坑了半天
                .build();

        // 实例化EventSource，注册EventSource监听器
        RealEventSource realEventSource = new RealEventSource(request, new EventSourceListener() {
            private long callStartNanos;

            private void printEvent(String name) {
//                long nowNanos = System.nanoTime();
//                if (name.equals("callStart")) {
//                    callStartNanos = nowNanos;
//                }
//                long elapsedNanos = nowNanos - callStartNanos;
//                System.out.printf("=====> %.3f %s%n", elapsedNanos / 1000000000d, name);
            }

            @Override
            public void onOpen(EventSource eventSource, Response response) {
//                printEvent("onOpen");
                sourceListener.onOpen(eventSource, response);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
//                printEvent("onEvent");
//                System.out.println(data);//请求到的数据
                sourceListener.onEvent(eventSource, id, type, data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
//                printEvent("onClosed");
                sourceListener.onClosed(eventSource);
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
//                printEvent("onFailure");//这边可以监听并重新打开
                sourceListener.onFailure(eventSource, t, response);
            }
        });
        realEventSource.connect(okHttpClient);//真正开始请求的一步
    }

}